<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/3/28
 * Time: 上午8:55
 * 余额变动操作
 */

namespace app\common\controller;


use app\common\model\CardCzgive;
use app\common\model\CardCzLog;
use app\common\model\CardMember;
use app\common\model\CardUserGet;
use app\common\model\CardUserLog;
use app\common\model\CardUserUpdate;
use app\common\model\Paylog;
use think\Controller;
use think\Request;
use Wechat\Wxobjopen;

class Balance extends Wxoption
{
//    public function _initialize(Request $request)
//    {
//        $param = $request->param();
//        $ActionLogs = new ActionLogs();
//        $ActionLogs->writelog("payos","web","balance","e:",$param);
//    }
    //余额核销
    public function hx_balance_del(){

    }

    //检查余额
    public function checkbalance($arr,$user,$card){
        if ($user['cs_balance'] <> 0) {
            //判断赠送金额是否超过核销金额
            $CardUserGet = new CardUserGet();
            if ($user['cs_balance'] < $arr['add_balance']) {
                //赠送金额归0
                $CardUserGet->where(['id'=>$user['id']])->setField('cs_balance', 0);
                $darr['del_balance'] = $arr['add_balance']-$user['cs_balance'];
            }else{
                $CardUserGet->where(['id'=>$user['id']])->setDec('cs_balance', $arr['add_balance']);
                $darr['del_balance'] = $arr['add_balance']-$arr['cs_balance'];
            }
        } else {
            //判断是否折扣
            if ($card['is_cz_discount'] == 1) {
                $discount = $card['discount'] / 100;
                $darr['del_balance'] = $arr['add_balance'] * $discount;
            }else{
                $darr['del_balance'] = $arr['add_balance'];
            }
        }
        $darr['add_balance'] = '';
        $darr['pay_balance'] = $arr['add_balance'];
        return $darr;
    }

    //更新记录 CardUserUpdate
    public function cardupdate($arr,$user,$arrc){
        $datas['code'] = $user['code'];
        $datas['card_id'] = $user['card_id'];
        $datas['openid'] = $user['openid'];
        if (isset($arr['record'])){
            $datas['record_balance'] = $arr['record'];
        }
        $datas['pay_balance'] = $arrc['pay_balance'];
        $datas['add_balance'] = $arrc['add_balance'];
        $datas['mid'] = $arr['mid'];
        if (isset($arr['giveid'])){
            $datas['giveid'] = $arr['giveid'];
        }
        if (isset($arr['del_balance'])){
            $datas['del_balance'] = $arrc['del_balance'];
        }
        if (isset($arr['add_bonus'])) {
            $datas['add_bonus'] = $arr['add_bonus'];
        }
        if (isset($arr['orderid'])){
            $datas['orderid'] = $arr['orderid'];
        }
        $datas['con_username'] = $arr['nickname'];
        $datas['hx_fs'] = $arr['hx_fs'];
        $datas['type'] = $arr['type'];
        $datas['cate'] = $arr['cate'];
        $datas['reason'] = $arr['reason'];
        $datas['source'] = $arr['source'];
        $datas['create_time'] = time();
        $CardUserUpdate = new CardUserUpdate();
        $resut = $CardUserUpdate->allowField(true)->save($datas);
        if ($resut){
            $updataid = $CardUserUpdate->id;
            $datas['up_id'] = $updataid;
            $datas['c_id'] = $user['c_id'];
            $datas['us_id'] = $user['id'];
            $datas['top_mid'] = $user['top_mid'];
            $datas['mid'] = $user['mid'];
            $datas['orderid'] = $arr['orderid'];
            $datas['nickname'] = $user['nickname'];
//            file_put_contents('/data2/html/payos/rec_user_fee.txt', '0:' . json_encode($datas) . PHP_EOL, FILE_APPEND);
//            $this->rec_user_fee($datas);

//            //积分
//            if ($datas['cate'] == 1 || isset($arr['add_bonus'])){
//
//                $datas['cate_type'] = 1;
//                $this->rec_cardlogs($datas);
//            //余额
//            }
//            if ($datas['cate'] == 1 || isset($arr['add_balance'])){
//                $datas['cate_type'] = 2;
//                $this->rec_cardlogs($datas);
//            }
        }else{
            $updataid = '';
        }
        return $updataid;
    }


    //增加余额记录
    /*
     *
     *
     */
    public function rec_user_fee($parem){
        try {
            $CardMember = new CardMember();
            $UserBonusFee = new UserBonusFee();
            if (isset($parem['con_username'])){$bonusb['con_username'] = $parem['con_username'];}else{$bonusb['con_username'] = $parem['nickname'];}
            if (isset($parem['record_balance'])){$bonusb['record_balance'] = $parem['record_balance'];}else{$bonusb['record_balance'] = '';}
            $bonusb['us_id'] = $parem['us_id'];
            $bonusb['top_mid'] = $parem['top_mid'];
            $bonusb['mid'] = $parem['mid'];
            $bonusb['c_id'] = $CardMember->where(['card_id' => $parem['card_id']])->value('id');
            $bonusb['openid'] = $parem['openid'];
            $bonusb['card_id'] = $parem['card_id'];
            $bonusb['code'] = $parem['code'];
            $bonusb['pay_cate'] = $parem['hx_fs'];
            $bonusb['balance'] = $parem['pay_balance'];
            $bonusb['cate'] = 2;
            $bonusb['reason'] = 3;
            $bonusb['source'] = $parem['source'];
            $bonusb['orderid'] = $parem['orderid'];
//            $UserBonusFee->rec_user_fee($bonusb, 1);
            if ($parem['pay_balance'] < $parem['add_balance']){
                $bonusb['cate'] = 2;
                $bonusb['reason'] = 2;
                $bonusb['balance'] = $parem['add_balance'] - $parem['pay_balance'];
//                $UserBonusFee->rec_user_fee($bonusb, 1);
            }
        }catch (\Exception $e) {
            $bonusdata = ['code' => 9999, 'message' => $e->getMessage()];
        }
    }


    //记录表
    public function rec_cardlogs($arr)
    {
//        file_put_contents('/data2/html/payos/cz_cardlogs.txt', 's:' . json_encode($arr), FILE_APPEND);
        try {
            $CardUserLog = new CardUserLog();
            $data['mid'] = $arr['mid'];
            $data['top_mid'] = $arr['top_mid'];
            $data['up_id'] = $arr['up_id'];
            $data['c_id'] = $arr['c_id'];
            $data['us_c_id'] = $arr['us_c_id'];
            $data['openid'] = $arr['openid'];
            $data['con_username'] = $arr['con_username'];
            $data['card_id'] = $arr['card_id'];
            $data['code'] = $arr['code'];
            //积分
            if ($arr['cate_type'] == 1){
                if (isset($arr['add_bonus'])) {
                    $data['num'] = $arr['add_bonus'];
                    $arr['cate'] = 1;
                }
            }
            //余额
            if ($arr['cate_type'] == 2){
                if (isset($arr['add_balance'])) {
                    $data['num'] = $arr['add_balance'];
                    $arr['cate'] = 2;
                }
            }

            if (isset($arr['record_balance'])){
                $data['record'] = $arr['record_balance'];           //记录
            }
            if (isset($arr['orderid'])) {
                $data['orderid'] = $arr['orderid'];
            }
            $data['type'] = $arr['type'];               //1充值/2核销
            $data['cate'] = $arr['cate'];               //1积分/2余额
            $data['reason'] = $arr['reason'];           //原因
            $data['source'] = $arr['source'];           //来源
            $data['create_time'] = time();
            $res = $CardUserLog->allowField(true)->save($data);

        }catch (\Exception $e) {
            $res = ['errcode' => 9999, 'message' => $e->getMessage()];
//            file_put_contents('/data2/html/payos/cz_cardlogs.txt', 'e:' . json_encode($res), FILE_APPEND);
        }
//        file_put_contents('/data2/html/payos/test.txt', 'bonus-1' . json_encode($res), FILE_APPEND);
    }

    //更新订单
    public function paylog_rec($arr){
        //订单记录
        $datalog['mid'] = $arr['mid'];
        $datalog['orderid'] = $this->getorder($arr['mid']);
        $datalog['pay_statu'] = 1;
        $datalog['price'] =  $arr['pay_balance'];
        $datalog['yf_price'] =  $arr['pay_balance'];
        $datalog['pay_time'] = date('Y-m-d H:i:s');
        $datalog['add_time'] = time();
        $datalog['pay_fs'] = 4;
        $datalog['d_cashier'] = $arr['nickname'];
        $Paylog = new Paylog();
        $Paylog->save($datalog);
        $res = $datalog;
//        if (isset($arr['updateid'])){
//            $datalog['updateid'] = $arr['updateid'];
//        }
        $this->isorderdel($datalog);
        return $res;
    }

    //判断上一笔充值状态，并删除该笔
    private function isorderdel($parem){
//        file_put_contents('/data2/html/payos/test.txt', 'czquee-1' . json_encode($parem), FILE_APPEND);
        try {
            $Paylog = new Paylog();
            $info = $Paylog->where(['orderid'=>$parem['orderid']])->field('mid,orderid,d_cashier')->find();
//            file_put_contents('/data2/html/payos/test.txt', 'czquee-2' . json_encode($info), FILE_APPEND);
            if ($info){
                $page = $Paylog->where(['mid'=>$info['mid'],'d_cashier'=>$info['d_cashier'],'pay_statu'=>1,'pay_fs'=>['in',[2,3]]])->order('id desc')->limit(1)->field('del_statu,orderid')->select();
//                file_put_contents('/data2/html/payos/test.txt', 'czquee-3' . json_encode($page), FILE_APPEND);
                if ($page) {
                    $isinfo = $page[0];
//                    file_put_contents('/data2/html/payos/test.txt', 'czquee-4' . json_encode($isinfo), FILE_APPEND);
                    if ($isinfo['del_statu'] == 0){
                        $gs = $Paylog->allowField(true)->save(['del_statu'=>1],['orderid'=>$isinfo['orderid']]);
//                        if (isset($parem['updateid'])) {
//                            $CardUserUpdate = new CardUserUpdate();
//                            $CardUserUpdate->save(['hx_fs'=>2],['id'=>$parem['updateid']]);
//                        }
//                        file_put_contents('/data2/html/payos/test.txt', 'czquee-5' . json_encode($gs), FILE_APPEND);
                        $del = $Paylog->where(['orderid'=>$parem['orderid']])->delete();
//                        file_put_contents('/data2/html/payos/test.txt', 'czquee-6' . json_encode($del), FILE_APPEND);
                    }
                }
            }
        }catch (\Exception $e) {
            $bondata = array('code' => 9099, 'message' => $e->getMessage());
        }
    }

    //更新充值记录
    public function cardczlog_rec($datalog,$user,$datas,$arr){
        $czdata['orderid'] = $datalog['orderid'];
        $czdata['openid'] = $user['openid'];
        $czdata['cz_price'] = $datas['pay_balance'];
        $czdata['zs_price'] = $datas['add_balance'] - $datas['pay_balance'];
        $czdata['giveid'] = $arr['giveid'];
        $czdata['statu'] = 1;
        $czdata['code'] = $user['code'];
        $czdata['addtime'] = $datalog['add_time'];
        $CardCzLog = new CardCzLog();
        $resut = $CardCzLog->allowField(true)->save($czdata);
        if ($resut){
            $give_rec_id = $CardCzLog->id;
            return $give_rec_id;
        }
    }

    //冲送判断
    public function cs_type($arr,$user){
        if (!empty($arr['giveid'])) {
            $CardZsgive = new CardCzgive();
            $givetype = $CardZsgive->where(['id'=>$arr['giveid']])->value('type');
            $ComCardPut = new CardPut();
            if ( $givetype == 1 ){
                $arrd['mid'] = $arr['mid'];
                $arrd['top_mid'] = $arr['top_mid'];
                $arrd['giveid'] = $arr['giveid'];
                $arrd['give_rec_id'] = $arr['give_rec_id'];
                $arrd['card_id'] = $user['card_id'];
                $arrd['openid'] = $user['openid'];
                $arrd['nickname'] = $user['nickname'];
                $arrd['code'] = $user['code'];
                $arrd['get_card_id'] = $user['id'];
                $resut = $ComCardPut->regSgive($arrd);        //新规则，赠送多张
//                $uend['zs_card'] = json_encode($resut['card'],JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'],JSON_UNESCAPED_UNICODE);
//                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id'=>$arr['updataid']])->update($uend);
                $res = 1;
            }else {
                //赠送方法
                $sparams['give_rec_id'] = $arr['give_rec_id'];
                $sparams['get_card_id'] = $user['id'];
                $sparams['card_id'] = $user['card_id'];
                $sparams['giveid'] = $arr['giveid'];
                $sparams['openid'] = $user['openid'];
                $sparams['nickname'] = $user['nickname'];
                $sparams['code'] = $user['code'];
                $resut = $ComCardPut->czgive($sparams);       //原规则
//                $uend['zs_card'] = json_encode($resut['card'],JSON_UNESCAPED_UNICODE);
//                $uend['zs_bonus'] = json_encode($resut['bonus'],JSON_UNESCAPED_UNICODE);
//                $CardUserUpdate = new CardUserUpdate();
//                $res = $CardUserUpdate->where(['id'=>$arr['updataid']])->update($uend);
                $res = 1;
            }

        }else{
            $res = 1;
        }
        return $res;
    }

    //获取订单号
    private function getorder($sh)
    {
        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
        return $order;
    }


    //余额更新微信操作  系统通知
    public function updatebalance($arr){
        //实例化微信
        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $data = [
            'code'=>$arr['code'],
            'card_id'=>$arr['card_id'],
            'custom_field_value2' => $arr['price'].'元',
            'notify_optional'=>[
                'is_notify_bonus'=>false,
                'is_notify_balance'=>false,
                'is_notify_custom_field2'=>false,
            ],
        ];
        $res = $WxObj->updateUserInfo($data);
        return $res;
    }
    
}